<?php

namespace App\Http\Controllers\Pay;

use App\Http\Controllers\Controller;
use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Yansongda\LaravelPay\Facades\Pay;
use Yansongda\Pay\Exception\ContainerException;
use Yansongda\Pay\Exception\InvalidParamsException;
use function Yansongda\Pay\get_wechat_public_certs;

class WechatController extends Controller
{
    public function notify(Request $request)
    {
        if ($request->input('type') === 1){
            $this->generateWechatPublicCeart();
            return apiResponse(msg: '密钥生成成功');
        }
        try {
            $res = Pay::wechat()->callback();
            Log::notice('回调信息');
            Log::notice($res);
            switch ($res['event_type']){
                case 'TRANSACTION.SUCCESS':
                    Log::info('这是支付成功回调');
                    $payData = $res['resource']['ciphertext'];
                    if($payData['trade_state'] == 'SUCCESS'){
                        $resUpdate =Order::payUpdate($payData['out_trade_no'],$payData['transaction_id'],$payData['amount']['total'],$payData['success_time']);
                        Log::info($resUpdate);
                        if ($resUpdate){
                            return Pay::wechat()->success();
                        }
                    }
                    break;
                case 'REFUND.SUCCESS':
                    Log::info('这是退款成功回调');
                    $refundData = $res['resource']['ciphertext'];
                    Order::where('order_number',$refundData['out_trade_no'])->update(['pay_status'=>5]);
                    return Pay::wechat()->success();
                case 'REFUND.ABNORMAL':
                    Log::info('这是退款异常回调');
                    break;
                case 'REFUND.CLOSED':
                    Log::info('这是退款关闭回调');
                    break;
            }

        } catch (ContainerException $e) {
            Log::error('ContainerException'.$e->getMessage());
        } catch (InvalidParamsException $e) {
            Log::error('InvalidParamsException'.$e->getMessage());
        }
        return apiResponse();
    }

    /**
     * 生成微信公钥证书
     */
    protected function generateWechatPublicCeart(){
        \Yansongda\Pay\Pay::config(config('pay'));
        $params = [
            '_config' => 'default' // 多租户配置时使用
        ];
        get_wechat_public_certs($params, storage_path('app/cert'));
    }
}
